'use strict';

const Controller = require('../../../core/common');

class BannersController extends Controller {

  async index() {
    const { ctx } = this;

    const { status, type, remark } = ctx.request.query;

    const attributes = ['id', 'cover', 'pathname', 'appId', 'click', 'createdAt', 'updatedAt'];
    const where = {};
    status && Object.assign(where, { status });
    type && Object.assign(where, { type });
    remark && Object.assign(where, { remark: { '$like': `%${remark}%` } });

    const data = await ctx.service.v1.banners.findAll({ attributes, where });

    this.success(data);
  }

  async show() {
    const { ctx } = this;

    const data = await ctx.service.v1.banners.findAll();

    this.success(data);
  }

  async create() {
    const { ctx } = this;

    const { cover, createdAt, endAt, pathname, openId, remark } = ctx.request.body;

    const data = await ctx.service.v1.banners.create(ctx.request.body);

    this.success(data);
  }

  async update() {
    const { ctx } = this;

    const { id = '' } = ctx.params;

    const { isEdit, status, type, ...body } = ctx.request.body;
    const params = {};
    const where = {};

    delete body.id;
    if (isEdit) {
      // 更新广告
      Object.assign(params, body);
      Object.assign(where, { id });
      // 上首页/详情页
    } else if (type === '1' || type === '2') {
      Object.assign(params, { type });
      Object.assign(where, {
        id: id.indexOf(',') === -1 ? id : { '$in': id.split(',') }
      });
    } else {
      // 下架广告
      Object.assign(params, { status });
      Object.assign(where, {
        id: id.indexOf(',') === -1 ? id : { '$in': id.split(',') }
      });
    }

    const data = await ctx.service.v1.banners.update(params, { where });

    this.success(data);
  }

  // 删除广告
  async destroy() {
    const { ctx } = this;

    const { id = '' } = ctx.params;

    const data = await ctx.service.v1.banners.destroy({
      where: {
        id: id.indexOf(',') === -1 ? id : { '$in': id.split(',') }
      }
    });

    this.success(data);
  }
}

module.exports = BannersController;